import { truthy, formatTime } from '@gnlab/utils'
import { message, Tag, Spin, Button, Popconfirm } from 'antd'
import { Actionable } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { ExternalContact } from '@/services/contact-types'
import { ContactType } from '@/services/contacts'
import './index.module.less'
import ChatFlow from './chat-flow'
import { default as ExtraInfo, type Ref as ExtraRef } from './extra-info'
import { default as Relation, type Ref as RelationRef } from './relation'

export const spin = <div styleName="loading">
  <Spin size="small" />
</div>
export const empty = <span styleName="empty">无</span>

export default function ExternalInfo() {
  const [contact] = useStreams(services.contacts.current.contact)
  if (!contact || contact.type !== ContactType.external) return null
  return <Content contact={contact} />
}

function Content(props: { contact: ExternalContact }) {
  const { contact } = props
  const [isAdmin] = useStreams(services.auth.isAdmin$)

  const relationRef = useRef<RelationRef>(null)
  const extraRef = useRef<ExtraRef>(null)
  function refresh() {
    //if (relationRef.current) relationRef.current.refresh()
    if (extraRef.current) extraRef.current.refresh()
    void services.externals.refreshInfo(contact.id)
  }

  const [deleting, setDeleting] = useState(false)
  async function remove() {
    setDeleting(false)
    const res = await services.externals.remove(contact.id)
    setDeleting(false)
    if (res.success) void message.success('客户已删除')
    else void message.error('客户删除失败：' + res.error)
  }

  return <div styleName="external-info-panel">
    <section styleName="base-info">
      <img src={contact.avatar || defaultAvatar} />
      <div styleName="contact-name">
        <div>
          {contact.name}
          {truthy(contact.deleted) ? <Tag styleName="deleted">删</Tag> : null}
        </div>
        {truthy(contact.deleted) ? (
          <div styleName="deleted-info">删除于 {formatTime(contact.deleted)}</div>
        ) : null}
      </div>
      <Actionable>
        <Button type="link" onClick={refresh}>
          刷新
        </Button>
        {isAdmin === true && !truthy(contact.deleted) ? (
          <Popconfirm title="确定要删除此客户吗？" onConfirm={remove} placement="topRight">
            <Button type="link" danger loading={deleting}>
              删除
            </Button>
          </Popconfirm>
        ) : null}
      </Actionable>
    </section>

    {/* contact 对象有可能重新生成，为避免不必要的重新渲染 / 数据加载，只传 contactId */}
    {/*<Relation contactId={contact.id} ref={relationRef} />*/}
    <ExtraInfo contactId={contact.id} ref={extraRef} />
    <Actionable>
      <ChatFlow contactId={contact.id} forGroup={false} />
    </Actionable>
  </div>
}
